<?php

namespace App\Exports;

use App\Models\ModelFields;
use App\Models\Models;
use App\Models\Order;
use App\Models\Product;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class OrderExport implements FromCollection, WithColumnFormatting, ShouldAutoSize,WithStyles
{
    /**订单导出**/
    private $params;
    private $title='订单列表';
    /**
     * @var string[] 导出标题集合
     */
    private $headingList = [
        ['订单列表','','','','','','','','','','','','','','','','','','','','','','',''],
        ['','','','','','','','','','','','','','','','','','','','','','','',''],
        ['id'=>'ID',
        'order_number'=>'订单编号',
        'customer_name'=>'客户名称',
        'serial_number'=>'订单流水号',
        'product_name'=>'产品名称',
        'model_number'=>'型号',
        'specification'=>'规格',
        'color'=>'颜色',
        'emergency_procedure'=>'紧急程度',
        'account_executive_id'=>'业务员',
        'receivables'=>'应收款',
        'received'=>'已收款',
        'num'=>'件数',
        'is_stock_up'=>'是否备货',
        'is_replenishment'=>'是否补货',
        'order_date' => '订单时间',
        'delivery_date' => '交货时间',
        'remark' => '备注'
        ]
    ];



    public function __construct($params) {
        ob_end_clean();
        $this->params = $params;
    }

    //数组转集合
    public function collection()
    {
        return new Collection($this->createData());
    }




    /**
     * Notes: 处理导出数据表头
     * User: q
     * DateTime: 2021/10/13 18:10
     * @return array
     */
    public function headings(): array{

        return  [
            "ID",
            "订单编号",
            "客户名称",
            "订单流水号",
            "产品名称",
            "型号",
            "规格",
            "颜色",
            "紧急程度",
            "业务员",
            "应收款",
            "定金",
            "件数",
            "是否备货",
            "是否补货",
            "接单日期",
            "交货日期",
            "备注",
        ];
    }


    public function createData(){
        $datas[] = $this->headingList;
        $params = $this->params;
        if($params['order_name'] == '订单列表'){
            $order = Order::Search($params);
        }elseif($params['order_name'] == '订单审核'){
            $order = Order::Audit($params);
        }elseif($params['order_name'] == '订单进度'){
            $order = Order::Schedule($params);
        }
        $data = $order->with(['color'=>function($q){
            return $q->select('id','color');
        },'product'=>function($q){
            return $q->select('id','product_name');
        },'customer'=>function($q){
            return $q->select('id','customer_name','customer_address');
        },'modelNumber'=>function($q){
            return $q->select('id','model_number');
        },'specification'=>function($q){
            return $q->select('id','specification');
        },'accountExecutive'=>function($q){
            return $q->select('id','company_name');
        }])
            ->orderBy('id','desc')->get()->toArray();
        if($data){
            foreach($data as $k=>$v){
                $product_id = $v['product_id'];
                $modelid = Product::where('id',$product_id)->value('modelid');
                $tablename = Models::where('modelid',$modelid)->value('tablename');
                $model_field = ModelFields::where('modelid',$modelid)->get();

                if($model_field){
                    foreach($model_field as $kk=>$vv){
                        if(in_array($vv->formtype,['input','textarea','inputnumber'])){
                            $data[$k]['models_field'][$vv->field] = DB::table($tablename)->where('order_id',$v['id'])->value($vv->field);
                        }else{
                            if(!empty($vv->option_list)){
                                $option_list = explode("\n",$vv->option_list);
                                //p($option_list);
                                $option_arr = [];
                                foreach($option_list as $key=>$val){
                                    $option = explode("|",rtrim($val));
                                    //p($option);
                                    $option_arr[$option[1]] = $option[0];
                                }
                                $field_key = DB::table($tablename)->where('order_id',$v['id'])->value($vv['field']);
                                $data[$k]['models_field'][$vv->field] = $field_key;
                                $data[$k]['models_field'][$vv->field."s"] = $option_arr[$field_key]??'';
                                //$data[$k]['models_field'][$vv->field] = ['value'=>$option_arr[$field_key]??'','key'=>$field_key];
                            }else{
                                $data[$k]['models_field'][$vv->field] = DB::table($tablename)->where('order_id',$v['id'])->value($vv['field']);
                            }
                        }
                    }
                }

            }
        }
        foreach ($data as $key=>&$val){
            $datas[] = [
                'id' => $val['id'],
                'order_number' => $val['order_number']??"",
                'customer_name' => $val['customer']['customer_name']??'',
                'serial_number' => $val['serial_number']??'',
                'product_name' => $val['product']['product_name']??'',
                'model_number' => $val['model_number']['model_number']??'',
                'specification' => $val['specification']['specification']??'',
                'color' => $val['color']['color']??'',
                //'size'=>$val['models_field']['size']??'',
                //'direction' => $val['direction']??'',
                'emergency_procedure'=>$this->getEmergencyProcedure($val['emergency_procedure']),
                'account_executive_id'=>$val['account_executive']['company_name']??'',
                'receivables'=>$val['receivables']??'',
                'received'=>$val['received']??'',
                'num'=>$val['num']??'',
                //'discount'=>$val['models_field']['discount'].'%',
                //'residual_payment'=>$val['models_field']['residual_payment'],
                //'collection_time'=>$val['models_field']['collection_time'],
                //'is_residual_payment'=>$this->getIsRes($val['models_field']['is_residual_payment']),
                'is_stock_up'=>$this->getIsRes($val['is_stock_up']),
                'is_replenishment'=>$this->getIsRes($val['is_replenishment']),
                'order_date' => $val['order_date']??'',
                'delivery_date' => $val['delivery_date']??'',
                'remark' => $val['remark']??'',
            ];
        }
        //p($datas);
        return $datas;
    }

    public function getEmergencyProcedure($value){
        if($value == 1){
            return '普通';
        }
        if($value == 2){
            return '紧急';
        }
        if($value == 3){
            return '十万火急';
        }
    }

    public function getIsRes($value){
        if($value == 1){
            return '是';
        }else{
            return '否';
        }
    }

    public function columnFormats(): array
    {
        //'B' => NumberFormat::FORMAT_DATE_DDMMYYYY, //日期
        $format = NumberFormat::FORMAT_NUMBER_00;//金额保留两位小数
        return ['M' => $format, 'N' => $format,'Q' => $format];

    }


    /**
     * sheet名称
     * @return string
     */
    public function title(): string
    {
        return $this->title;
    }

    /**
     * 设置列宽
     * @return array
     */
    public function columnWidths(): array
    {
        return [
            'A' => 100, 'B' => 100, 'C' => 100, 'D' => 100, 'E' => 100, 'F' => 100,'G' => 100
        ];
    }




    public function styles(Worksheet $sheet)
    {
        $sheet->getDefaultRowDimension()->setRowHeight(22);//设置行高
        $sheet->mergeCells('A1:X2'); //合并单元格
        $sheet->getStyle('A1:X2')
            ->applyFromArray([
                'font' => ['bold' => true],
                'color' => ['rgb' => '0072ff']
            ]);//字体设置
        // 设置背景色
        $sheet->getStyle('A1:X2')->getFill()
            ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
            ->getStartColor()->setRGB('e9e9e9');

        // setWrapText自动换行，setVertical垂直对齐方式
        $sheet->getStyle("A:X")->getAlignment()->setVertical('center');
        $sheet->getStyle('A:X')->applyFromArray(['alignment' => ['horizontal' => 'center']]);//设置水平居中


    }


}
